package com.hqyj.am.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class EmailSend {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String myEmail;

    /**
     *
     * @param toEmail 收件人
     * @param
     * @param
     * @return
     */
    public boolean send(String toEmail){
        Random rd = new Random();
        String code = rd.nextInt(10000)+"";


        //信封
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人
        message.setFrom(myEmail);
        //收件人
        message.setTo(toEmail);
        //标题
        message.setSubject("验证码");
        //正文
        message.setText(code);

        try{
            redisTemplate.opsForValue().set("code:"+toEmail,code,1, TimeUnit.MINUTES);
            javaMailSender.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }

        return false;
    }
}
